//
//  AddNewBillTypeViewController.m
//  iEasyBill
//
//  Created by student on 14-6-13.
//  Copyright (c) 2014年 com.yly16. All rights reserved.
//

#import "AddNewBillTypeViewController.h"

@interface AddNewBillTypeViewController ()
@property (strong , nonatomic)iBillType *aType;       //账单类别
@property (strong , nonatomic)iBillAccount *iAccount; //账单账户
@property (strong , nonatomic)NSArray *imageList;

@property (strong , nonatomic)UIImageView *imageView;
@property (strong , nonatomic)UITextField *textField;
@property (strong , nonatomic)UITableView *subTableView;
@property (strong , nonatomic)UISegmentedControl *payoutSegmented;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@end

@implementation AddNewBillTypeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.indexPathArray = [[NSMutableArray alloc]init];
    self.SubTypeArray = [[NSMutableArray alloc]init];
    isSub = NO;
    if (self.aType != nil) {
        self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(30, 80, 100, 100)];
        self.imageView.image =[UIImage imageNamed:@"camo.png"];
        self.imageView.layer.borderWidth = 3;
        self.imageView.layer.masksToBounds = YES;
        self.imageView.layer.cornerRadius = 20;
        [self.view addSubview:self.imageView];
        
        NSArray *segmentedArray = [[NSArray alloc]initWithObjects:@"收入",@"支出",nil];
        self.payoutSegmented = [[UISegmentedControl alloc]initWithItems:segmentedArray];
        self.payoutSegmented.frame = CGRectMake(150, 80, 140, 30);
        self.payoutSegmented.selectedSegmentIndex = 0;//设置默认选择项索引
        self.payoutSegmented.tintColor = [UIColor greenColor];
        　　//有基本四种样式
        self.payoutSegmented.segmentedControlStyle = UISegmentedControlStylePlain;//设置样式
        [self.view addSubview:self.payoutSegmented];
        
        UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(150, 110, 150, 36)];
        nameLabel.text = @"账单名称：";
        [self.view addSubview:nameLabel];
        
        self.textField = [[UITextField alloc]initWithFrame:CGRectMake(150, 140, 140, 40)];
        self.textField.borderStyle = UITextBorderStyleRoundedRect;
        [self.view addSubview:self.textField];
        
        UIButton *imgBt = [UIButton buttonWithType:UIButtonTypeCustom];
        imgBt.frame = CGRectMake(30, 80, 100, 100);
        [imgBt addTarget:self action:@selector(chooseImage:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:imgBt];
        
        UIButton *saveTypeBt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        saveTypeBt.frame = CGRectMake(30, 185, 260, 40);
        saveTypeBt.backgroundColor = [UIColor grayColor];
        saveTypeBt.layer.masksToBounds = YES;
        saveTypeBt.layer.cornerRadius = 20;
        [saveTypeBt setTintColor:[UIColor greenColor]];
        [saveTypeBt setTitle:@"保存账单父类别" forState:UIControlStateNormal];
        [saveTypeBt addTarget:self action:@selector(saveNewType:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:saveTypeBt];
        
        UIButton *addSubTypeBt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        addSubTypeBt.frame = CGRectMake(30, 230, 120, 40);
        addSubTypeBt.backgroundColor = [UIColor grayColor];
        addSubTypeBt.layer.masksToBounds = YES;
        addSubTypeBt.layer.cornerRadius = 20;
        [addSubTypeBt setTintColor:[UIColor greenColor]];
        [addSubTypeBt setTitle:@"➕添加子类别" forState:UIControlStateNormal];
        [addSubTypeBt addTarget:self action:@selector(addNewSubType:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:addSubTypeBt];
        
        UIButton *saveSubTypeBt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        saveSubTypeBt.frame = CGRectMake(170, 230, 120, 40);
        saveSubTypeBt.backgroundColor = [UIColor grayColor];
        saveSubTypeBt.layer.masksToBounds = YES;
        saveSubTypeBt.layer.cornerRadius = 20;
        [saveSubTypeBt setTintColor:[UIColor greenColor]];
        [saveSubTypeBt setTitle:@"保存账单子类别" forState:UIControlStateNormal];
        [saveSubTypeBt addTarget:self action:@selector(saveNewSubTypes:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:saveSubTypeBt];
        
        subTypeNumber = 0;
        self.subTableView = [[UITableView alloc]initWithFrame:CGRectMake(30, 280, 260, 44) style:UITableViewStylePlain];
        [self.subTableView setHidden:YES];
        self.subTableView.dataSource = self;
        self.subTableView.delegate = self;
        [self.view addSubview:self.subTableView];
    }else{
        
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(BOOL)canBecomeFirstResponder{
    return YES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.textField resignFirstResponder];
    for (NSIndexPath *index in self.indexPathArray) {
        UITableViewCell *cell = [self.subTableView cellForRowAtIndexPath:index];
        UITextField *textFiled = (UITextField*)[cell viewWithTag:101];
        [textFiled resignFirstResponder];
    }
    [self.collectionView setHidden:YES];
}
//TODO:>>>>>
-(void)saveNewType:(id)sender{
    self.aType.typeName = self.textField.text;
    self.aType.typeImageData = UIImagePNGRepresentation(self.imageView.image);
    self.aType.typeIsPayOut = [NSNumber numberWithBool:self.payoutSegmented.selectedSegmentIndex];
    [[DatabaseManager shareManager]addNewBillType:self.aType];
}
-(void)addNewSubType:(id)sender{
    iBillTypeSub *sub = [[iBillTypeSub alloc]init];
    [self.SubTypeArray addObject:sub];
    subTypeNumber ++;
    [self.subTableView setHidden:NO];
    if (subTypeNumber > 4) {
        self.subTableView.frame = CGRectMake(30, 280, 260, 44*4);
    }
    else{
        self.subTableView.frame = CGRectMake(30, 280, 260, 44*subTypeNumber);
    }
    [self.subTableView reloadData];
}
-(void)saveNewSubTypes:(id)sender{
    
    
}
-(void)chooseImage:(UIButton*)sender
{
    subIndexPath = [self indexsPathFromView:sender];
    if (sender.tag == 103) {
        isSub = YES;
    }
    else{
        isSub = NO;
    }
    UIActionSheet *actt = [[UIActionSheet alloc]initWithTitle:@"本地图片选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"本地图片" otherButtonTitles:@"DIY", nil];
    [actt showInView:self.view];
}
-(void)closeSubType:(UIButton*)sender{
    NSIndexPath *index = [self indexsPathFromView:sender];
    [self.SubTypeArray removeObjectAtIndex:index.row];
    subTypeNumber --;
    //NSIndexPath *indexpath = [self indexsPathFromView:sender];
    if (subTypeNumber > 4) {
        self.subTableView.frame = CGRectMake(30, 280, 260, 44*4);
    }
    else{
        self.subTableView.frame = CGRectMake(30, 280, 260, 44*subTypeNumber);
    }
    [self.subTableView reloadData];
}
-(NSIndexPath*)indexsPathFromView:(UIView*)view
{
    UIView *parentView = [view superview];
    
    while (![parentView isKindOfClass:[UITableViewCell class]] && parentView!=nil) {
        parentView = parentView.superview;
    }
    NSIndexPath *indexPath = [self.subTableView indexPathForCell:(UITableViewCell*)parentView];
    NSLog(@"%d",indexPath.row);
    return indexPath;
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"本地图片"]) {
        [self.collectionView setHidden:YES];
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
            UIImagePickerController *pickerView = [[UIImagePickerController alloc]init];
            
            pickerView.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
            pickerView.delegate = self;
            pickerView.allowsEditing= YES;
            [self presentViewController:pickerView animated:YES completion:nil];
        }
    }
    if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"DIY"]) {
        NSString *path = [[NSBundle mainBundle]pathForResource:@"newTypeImage" ofType:@"plist"];
        //NSArray *array = [[NSArray alloc]initWithContentsOfFile:path];
        self.imageList = [[NSArray alloc]initWithContentsOfFile:path];

        [self.collectionView setHidden:NO];
        self.collectionView.backgroundColor =[UIColor clearColor];
        [self.view addSubview:self.collectionView];
        self.collectionView.dataSource = self;
        self.collectionView.delegate = self;
        
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    
    if (isSub == YES) {
        iBillTypeSub *sub = [self.SubTypeArray objectAtIndex:subIndexPath.row];
        sub.typeSubImageData = UIImageJPEGRepresentation(image, 1);
        [self.subTableView reloadData];
    }else{
        self.imageView.image = image;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark self.collectionView dataSource delegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.imageList.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    //显示第一个cell
    static NSString *CellIdentifier = @"Cell";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    
    UIImageView *imageView =[[UIImageView alloc]initWithFrame:cell.bounds];
    imageView.image = [UIImage imageNamed:[self.imageList objectAtIndex:indexPath.row]];
    [cell addSubview:imageView];
    
    return cell;
}
//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//    return CGSizeMake(100,100);
//}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%d",indexPath.row);
    
    if (isSub == YES) {
        iBillTypeSub *sub = [self.SubTypeArray objectAtIndex:subIndexPath.row];
        UIImage *image =[UIImage imageNamed:[self.imageList objectAtIndex:indexPath.row]];
        sub.typeSubImageData = UIImageJPEGRepresentation(image, 1);
        [self.subTableView reloadData];
    }else{
        self.imageView.image = [UIImage imageNamed:[self.imageList objectAtIndex:indexPath.row]];
    }
    
}
#pragma mark tableView代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    [self.indexPathArray removeAllObjects];
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return subTypeNumber;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *TableSampleIdentifier = @"TableSampleIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             TableSampleIdentifier];
    [self.indexPathArray addObject:indexPath];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:TableSampleIdentifier];
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 2, 40, 40)];
        [cell addSubview:imageView];
        imageView.tag=100;
        
        UITextField *nameText = [[UITextField alloc]initWithFrame:CGRectMake(60, 5, 150, 35)];
        nameText.borderStyle = UITextBorderStyleRoundedRect;
        nameText.tag = 101;

        [cell addSubview:nameText];
        
        UIButton *closeBt = [UIButton buttonWithType:UIButtonTypeCustom];
        closeBt.frame = CGRectMake(220, 3, 35, 35);
        closeBt.tag = 102;
        [cell addSubview:closeBt];
        
        UIButton *chooseImageBt = [UIButton buttonWithType:UIButtonTypeCustom];
        chooseImageBt.frame = CGRectMake(10, 2, 40, 40);
        chooseImageBt.tag = 103;
        [cell addSubview:chooseImageBt];
        
    }
    iBillTypeSub *sub = [self.SubTypeArray objectAtIndex:indexPath.row];
    
    
    cell.layer.cornerRadius = 15;
    cell.layer.masksToBounds = YES;
    cell.backgroundColor = [UIColor grayColor];
    UIImageView *imageView = (UIImageView*)[cell viewWithTag:100];
    imageView.image = [UIImage imageNamed:@"camo.png"];
    if (sub.typeSubImageData.length != 0) {
        imageView.image = [UIImage imageWithData:sub.typeSubImageData];
    }
    
    UITextField *nameText = (UITextField*)[cell viewWithTag:101];
    nameText.placeholder = @"请输入子类别名称";
    if (sub.typeSubName.length != 0) {
        nameText.text = sub.typeSubName;
    }
    UIButton *closeBt = (UIButton*)[cell viewWithTag:102];
    [closeBt addTarget:self action:@selector(closeSubType:) forControlEvents:UIControlEventTouchUpInside];
    [closeBt setImage:[UIImage imageNamed:@"calse.png"] forState:UIControlStateNormal];
    
    UIButton *chooseImageBt = (UIButton*)[cell viewWithTag:103];
    [chooseImageBt addTarget:self action:@selector(chooseImage:) forControlEvents:UIControlEventTouchUpInside];
    
    
    return cell;
}
@end
